<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\common\controller;

use QRcode;
use think\Controller;
use app\common\model\Money as MoneyM;
use app\common\model\Users as UsersM;
use app\common\model\Msg as MsgM;
use think\Db;
use think\facade\Env;

/**
 * 项目公共控制器
 * @package app\common\controller
 */
class Core extends Controller
{
    /**
     * 通过地址和件数计算运费
     * @param $addr   邮寄地址
     * @param $weight  商品重量
     * @param $express_template_id  快递模板id
     * @return int|string
     */
    public function get_freight($addr,$weight,$express_template_id){
        $freight = 0;
        $express_template_info = Db::name('express_delivery')->where(['id'=>$express_template_id])->find();

        //包邮
        if($express_template_info['is_free'] == 1){
            $freight = 0;
            return  $freight;
        }
        $express_template_info['child1'] =Db::name('express_shipping_method')
            ->where(['template_id' => $express_template_id])
            ->select();
        $express_template_info['child2'] = Db::name('express_free')
            ->where(['template_id'=>$express_template_id])
            ->select();
        $city_id =Db::name('qt_area')
            ->where(['name'=>$addr,'level'=>1])
            ->value('id');
        //首先判断地址在不在child1中，如果在的话就按其规则计算，如果不在就按通用运费计算
        if(!empty($express_template_info['child1'])){
            foreach ($express_template_info['child1'] as $i => $node){
                if(in_array($city_id,explode(',',$node['fast_address']))){
                    //按照指定地区的快递费用规则计算
                    if($weight <= $node['first_weight']){
                        $freight = $node['first_amount'];
                        return $freight;
                    }else{
                        if($node['add_weight']){
                            $continue_weight = bcdiv(($weight - $node['first_weight']) , $node['add_weight'],2);
                            $continue_weight = ceil($continue_weight);// 进一法, 不足一公斤 也按一公斤算
                            $freight = $node['first_amount'] +  bcmul($continue_weight,$node['add_amount'],2) ;
                            return $freight;
                        }else{
                            $freight = $node['first_amount'];
                            return $freight;
                        }
                    }
                }
            }
        }
        //判断是否在包邮地区
        if(!empty($express_template_info['child2'])){
            foreach ($express_template_info['child2'] as $j => $val){
                if(in_array($city_id,explode(',',$val['address']))){
                    if($weight <= $val['weight']){
                        $freight = 0;
                        return  $freight;
                    }
                }
            }
        }
        //获取默认件数
        $default_weight = $express_template_info['default_weight'];
        //获取默认运费
        $default_price = $express_template_info['default_price']  ;
        //按默认规则计算运费
        if($weight <= $default_weight){
            $freight = $default_price;
        }else{
            if($express_template_info['add_weight']){
                //公式 (总重量 - 首重) * 续重价格 + 首重价格 = 运费
                $continue_weight = bcdiv(($weight - $default_weight) , $express_template_info['add_weight'],2);
                $continue_weight = ceil($continue_weight);// 进一法, 不足一公斤 也按一公斤算
                $freight = $default_price +  bcmul($continue_weight,$express_template_info['add_price'],2) ;
            }else{
                $freight = $default_price;
            }
        }
        return $freight;
    }

    /**
     *  用户资金变动记录
    **/
    public function viper_add_log($user_id,$money,$check,$type,$flag,$content){
        $user=Db::name('qt_user_viper')->where('id',$user_id)->find();
        if($flag=='1')
        {
            $m='money';
        }else if($flag=='2')
        {
            $m='point';
        }else
            {
            return $msg = ['code' => '204', 'msg' => '变动类型错误', 'data' => ''];
        }
        if($check=='1'){
            $after=$user[$m]+$money;
        }else{
            $after=$user[$m]-$money;
            if($after<0){
                return $msg = ['code' => '204', 'msg' => '账户余额不足', 'data' => ''];
            }
        }

        if($money<=0)
        {
            return $msg = ['code' => '204', 'msg' => '错误的变动数量', 'data' => ''];
        }

        if(!is_numeric($money))
        {
            return $msg = ['code' => '204', 'msg' => '错误的变动数量', 'data' => ''];
        }

        $log = array(
            'money'         =>  $money,
            'after_money'   =>  $after,
            'check'         =>  $check,
            'type'          =>  $type,
            'create_time'   =>  time(),
            'uv_id'         =>  $user_id,
            'content'       =>  $content,
            'flag'          =>  $flag,
        );
        try {
            Db::startTrans();
            if($check=='1')
            {
                Db::name('qt_user_viper')
                    ->where('id', $user_id)
                    ->inc($m, $money)
                    ->update();
            }else{
                Db::name('qt_user_viper')
                    ->where('id', $user_id)
                    ->dec($m, $money)
                    ->update();
            }
            Db::name('qt_viper_money_log')->insert($log);
            Db::commit();
            $res=true;
        } catch (\Exception $exception) {
            Db::rollback();
            $res=false;
        }
        if($res){
            return $msg = ['code' => '200', 'msg' => '变动成功', 'data' => ''];
        }else{
            return $msg = ['code' => '204', 'msg' => $exception->getMessage(), 'data' => ''];
        }
    }



    /**
     * @param $user_id  用户id
     * @param $money   变动金额
     * @param $check  1 增加2 减少
     * @param $type  类型
     * @param $flag  1 账户余额 2 积分
     * @param $content 变动描述
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function add_log($user_id,$money,$check,$type,$flag,$content){
        $user=Db::name('qt_users')->where('id',$user_id)->find();
        if($flag=='1'){
            $m='money';
            $am='all_money';

        }else if($flag=='2'){
            $m='point';
            $am='all_point';
        }else{
            return $msg = ['code' => '204', 'msg' => '变动类型错误', 'data' => ''];
        }
        if($check=='1'){
            $after=$user[$m]+$money;
        }else{
            $after=$user[$m]-$money;
            if($after<0){
                return $msg = ['code' => '204', 'msg' => '账户余额不足', 'data' => ''];
            }
        }
        if($money<=0){
            return $msg = ['code' => '204', 'msg' => '错误的变动数量', 'data' => ''];
        }
        if(!is_numeric($money)){
            return $msg = ['code' => '204', 'msg' => '错误的变动数量', 'data' => ''];
        }
        $log = array(
            'money' => $money,
            'after_money' => $after,
            'check' => $check,
            'type'=>$type,
            'create_time' => time(),
            'user_id' => $user_id,
            'content' => $content,
            'flag' => $flag,
        );
        try {
            Db::startTrans();
            if($check=='1'){
                Db::name('qt_users')
                    ->where('id', $user_id)
                    ->inc($m, $money)
                    ->inc($am, $money)
                    ->update();
            }else {
                Db::name('qt_users')
                    ->where('id', $user_id)
                    ->dec($m, $money)
                    ->update();
            }
            Db::name('qt_money_log')->insert($log);
            Db::commit();
            $res=true;
        } catch (Exception $exception) {
            Db::rollback();
            $res=false;
        }
       if($res){
           return $msg = ['code' => '200', 'msg' => '变动成功', 'data' => ''];
       }else{
           return $msg = ['code' => '204', 'msg' => $exception->getMessage(), 'data' => ''];
       }
    }

    /**
     * @param $id 订单id
     * @param $flag 订单类型 1 普通订单 2 积分订单 3 秒杀订单  4拼团订单
     * @param $type 发货类型 1 发货 2 退货
     * @param $exp_name 快递名称
     * @param $exp_no 快递单号
     * 发货
     */
    public function send($id,$flag,$type,$exp_name,$exp_no){
        if($type=='1'){
            $table='qt_order';
        }elseif ($type=='2'){
            $table='qt_point_order';
        }elseif ($type=='3'){
            $table='qt_seckill_order';
        }elseif ($type=='4'){
            $table='qt_group_order';
        }elseif($type=='5'){
            $table='qt_invoice_log';
        }
        else{
            return $msg = ['code' => '204', 'msg' => '错误的订单类型', 'data' => ''];
        }
        $order=Db::name($table)->where('id',$id)->find();
        if($type!='1' && $type!='5'){
            if($order['status']!='2'){
                return $msg = ['code' => '204', 'msg' => '该订单不是发货状态', 'data' => ''];
            }
        }
        $express=Db::name('qt_express')->where('id',$exp_name)->find();
        $up=array(
            'order_id'=>$id,
            'type'=>$type,
            'flag'=>$flag,
            'exp_id'=>$express['id'],
            'exp_name'=>$express['name'],
            'exp_no'=>$exp_no,
            'short_name'=>$express['short_name'],
            'create_time'=>time(),
        );
        try {
            Db::startTrans();
            Db::name('qt_order_express')->insert($up);
            if($table == 'qt_invoice_log'){
                Db::name($table)->where('id',$id)->update(['open_time'=>time(),'status'=>'2']);
            }else{
                Db::name($table)->where('id',$id)->update(['deliver_time'=>time(),'status'=>'3']);
            }
            Db::commit();
            $res=true;
        } catch (Exception $exception) {
            Db::rollback();
            $res=false;
        }
        if($res){
            return $msg = ['code' => '200', 'msg' => '发货成功', 'data' => ''];
        }else{
            return $msg = ['code' => '204', 'msg' => $exception->getMessage(), 'data' => ''];
        }
    }

}